<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager
;

use app\common\constant\Constant;
use app\common\model\CaptainApplication;
use app\common\model\Region;
use think\Db;
use think\Exception;

class RegionManager extends BaseManager
{


    public static function getRegion($pid=0,$level=1):array
    {
        $data = [];
        try {
            if ($level==1){
                $redis = new \Redis();
                $config = config('redis');
                $redis->connect($config['host'], $config['port']);
                if ($config['password']){
                    $redis->auth($config['password']);
                }
                $data = $redis->get($config['prefix'].Constant::REGION_KEY) ?? [];
                if (empty($data)){
                    $provinceData = Region::where('parent_id',100000)->where('statusswitch',Region::STATUS_ENABLE)->where('level_type',Region::LEVEL_PROVINCE)->field('city_code,name,parent_id,level_type')->select();
                    if ($provinceData){
                        foreach ($provinceData as $pk=>&$pv){
                            $cityData = Region::where('parent_id',$pv['city_code'])->where('level_type',Region::LEVEL_CITY)->where('statusswitch',Region::STATUS_ENABLE)->field('city_code,name,parent_id,level_type')->select();
                            $pv['data'] = $cityData;
                            if ($cityData){
                                foreach ($cityData as $ck=>&$cv){
                                    $districtData = Region::where('parent_id',$cv['city_code'])->where('level_type',Region::LEVEL_DISTRICT)->where('statusswitch',Region::STATUS_ENABLE)->field('city_code,name,parent_id,level_type')->select();
                                    $cv['data'] = $districtData;
                                }
                            }
                        }
                        $redis->set($config['prefix'].Constant::REGION_KEY,json_encode($provinceData,JSON_UNESCAPED_UNICODE));
                        $data = $redis->get($config['prefix'].Constant::REGION_KEY) ?? [];
                    }
                }
                $data = json_decode($data,true);
            }else{
                $where['parent_id'] = $pid;
                $where['level_type'] = $level;
                $data = Region::where($where)->where('statusswitch',Region::STATUS_ENABLE)->field('city_code,name,parent_id,level_type')->select();
            }

            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){

            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>$data];
    }
}